<template>
  <div>
    <el-empty v-if="!data?.length" description="提交任务后将在此显示生成进度" />
    <template v-else>
      <el-timeline style="max-width: 600px">
        <el-timeline-item
          v-for="(item, index) in data"
          :key="index"
          :timestamp="item.updateTime"
        >
          {{ item.des }}
        </el-timeline-item>
      </el-timeline>
      <el-button @click="handleClick" type="primary" style="width: 100%"
        >查看生成记录</el-button
      >
    </template>
  </div>
</template>
<script setup>
import { onBeforeUnmount, shallowRef, watch } from 'vue';
import { getTaskLogPage } from '../../api/task';
import { useRouter } from 'vue-router';

const props = defineProps({
  taskId: {
    default: '',
  },
});

const router = useRouter();

const data = shallowRef([]);

const timer = ref();

const fetchData = async () => {
  const res = await getTaskLogPage({
    taskId: props.taskId,
  });
  data.value = res.data;
};

const intervalGetTaskLog = () => {
  clearInterval(timer.value);
  fetchData();
  timer.value = setInterval(fetchData, 5000);
};

const handleClick = () => {
  router.push({ path: '/log' });
};

watch(
  () => props.taskId,
  async (newTaskId) => {
    if (!newTaskId) {
      data.value = [];
      clearInterval(timer.value);
      return;
    }
    intervalGetTaskLog();
    // const res = await getTaskLogPage({
    //   taskId: newTaskId,
    // });
    // data.value = res.data;
  },
  {
    immediate: true,
  },
);

onBeforeUnmount(() => {
  clearInterval(timer.value);
});
</script>
